package com.yanqu.road.web.controller.usercenter.newadmin;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.impl.admin.AdminCommonDaoImpl;
import com.yanqu.road.dao.impl.servercenter.CrossServerInfoDaoImpl;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.admin.AdminResult2;
import com.yanqu.road.entity.enums.eChannelType;
import com.yanqu.road.entity.servercenter.CrossServerInfo;
import com.yanqu.road.entity.servercenter.ProcessInfo;
import com.yanqu.road.entity.servercenter.ServerGroup;
import com.yanqu.road.entity.web.ICrossWebService;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.CrossServerType;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.WebServer;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 27 跨服榜单分组
 */
@RestController
@RequestMapping("/usercenter/admin")
public class CenterCrossServerGroupController {


    /**
     *  27.1 跨服榜单分组查询
     */
    @ResponseBody
    @RequestMapping(value = "getCrossServerGroupList", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String getCrossServerGroupList(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        int channelId = jsonObject.getIntValue("channelId");
        Map<Integer, ServerGroup> groupConfigMap = new AdminCommonDaoImpl().getServerGroupMap(channelId);

        eChannelType channelType = eChannelType.forValue(channelId);
        AdminResult2 result2 = AdminResult2.defaultInstance();
        for (Map.Entry<Integer, ServerGroup> entry : groupConfigMap.entrySet()) {
            JSONObject object = new JSONObject();
            ServerGroup group = entry.getValue();
            object.put("channelId", channelId);
            object.put("groupId", group.getGroupId());
            object.put("channelName", channelType.getName());
            object.put("serverIds", group.getServerListStr());
            object.put("rankFlag", group.isCrossRank() ? 1 : 0);
            object.put("chatFlag", group.isCrossChat() ? 1 : 0);
            object.put("wealthFlag", group.getCrossMammonState());
            result2.getData().add(object);
        }
        return result2.toJsonString();
    }

    /**
     *  27.2 新增跨服榜单分组
     */
    @ResponseBody
    @RequestMapping(value = "addCrossServerGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String addCrossServerGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        JSONArray list = jsonObject.getJSONArray("list");
        if(list.size() == 0){
            return AdminResult.failMsg("参数有误").toJsonString();
        }

        int maxGroupId = new AdminCommonDaoImpl().getCrossServerGroupMaxId();

        int changTime = DateHelper.getCurrentSecond();
        List<ServerGroup> addList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject object = list.getJSONObject(i);
            int channelId = object.getIntValue("channelId");
            String serverIds = object.getString("serverIds");
            int rankFlag = object.getIntValue("rankFlag");
            int chatFlag = object.getIntValue("chatFlag");
            int wealthFlag = object.getIntValue("wealthFlag");
            ServerGroup data = new ServerGroup();
            data.setGroupId(++maxGroupId);
            data.setCrossRank(rankFlag == 1);
            data.setCrossMammonState(wealthFlag);
            data.setCrossChat(chatFlag == 1);
            data.setServerList(StringUtils.stringToLongList(serverIds, ","));
            data.setServerListStr(serverIds);
            data.setChannelId(channelId);
            addList.add(data);
        }

        boolean result = new AdminCommonDaoImpl().batchInsertServerGroup(addList, changTime);
        if(!result){
            return AdminResult.failMsg("失败").toJsonString();
        }

        return AdminResult.defaultInstance().toJsonString();

    }

    /**
     *  27.3 修改跨服榜单分组
     */
    @ResponseBody
    @RequestMapping(value = "updateCrossServerGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String updateCrosstServerGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int channelId = jsonObject.getIntValue("channelId");
        int groupId = jsonObject.getIntValue("groupId");
        int rankFlag = jsonObject.getIntValue("rankFlag");
        String serverIds = jsonObject.getString("serverIds");
        int chatFlag = jsonObject.getIntValue("chatFlag");
        int wealthFlag = jsonObject.getIntValue("wealthFlag");
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("groupId", groupId);
        dataMap.put("crossRank", rankFlag);
        dataMap.put("crossChat", chatFlag);
        dataMap.put("crossMammon", wealthFlag);
        dataMap.put("changTime", DateHelper.getCurrentSecond());
        dataMap.put("serverList", serverIds);
        dataMap.put("channelId", channelId);
        int changTime = DateHelper.getCurrentSecond();
        boolean result = new AdminCommonDaoImpl().updateCrossServerGroup(dataMap, changTime);
        if(!result){
            return AdminResult.failMsg("失败").toJsonString();
        }
        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     *  27.4 删除跨服榜单分组
     */
    @ResponseBody
    @RequestMapping(value = "delCrossServerGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String delCrossServerGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        int channelId = jsonObject.getIntValue("channelId");
        int groupId = jsonObject.getIntValue("groupId");
        boolean result = new AdminCommonDaoImpl().deleteServerServerGroup(groupId, channelId);
        if(!result){
            return AdminResult.failMsg("失败").toJsonString();
        }
        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     *  27.6 刷新跨服分组
     */
    @ResponseBody
    @RequestMapping(value = "reloadCrossServerGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String reloadCrossServerGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        int channelId = jsonObject.getIntValue("channelId");

        List<ProcessInfo> processInfoList = new ArrayList<>();

        List<CrossServerInfo> serverInfoList = new CrossServerInfoDaoImpl().getAllChannelCrossServerInfo(channelId);
        serverInfoList.removeIf(next -> (next.getCrossServerType() != CrossServerType.RANK_CROSS_1) && next.getCrossServerType() != CrossServerType.BANQUET_CROSS);

        for (CrossServerInfo crossServerInfo : serverInfoList) {
            if(Config.isDebug() && crossServerInfo.getCrossServerId() != 99900077 && crossServerInfo.getCrossServerId() != 99905020 && crossServerInfo.getCrossServerId() != 99905001){
                continue;
            }

            for (ProcessInfo processInfo : crossServerInfo.getProcessInfoList()) {
                if(processInfo.getServerName().equals("cross_server")) {
                    processInfoList.add(processInfo);
                }
            }
        }

        ExecutorService webExecutor = WebServer.getWebExecutor();
        List<Long> errorCrossServerIdList = new ArrayList<>();
        try {
            //遍历异步通知活动跨服
            CountDownLatch countDownLatch = new CountDownLatch(processInfoList.size());
            JSONObject param = new JSONObject();
            param.put("content", "ServerGroupMgr");
            for (ProcessInfo processInfo : processInfoList) {
                webExecutor.execute(() -> {
                    try {
                        String url = "http://" + processInfo.getAddress() + ":" + processInfo.getAdminPort() + "/crossws?wsdl";
                        QName qName = new QName("http://webservice.server.road.yanqu.com/", "GrossWebServiceService");
                        Service service = Service.create(new URL(url), qName);
                        ICrossWebService crossWebService = service.getPort(ICrossWebService.class);
                        String resp = crossWebService.executeAdminOperate("AgentReload|reloadMgr", param.toJSONString(), "Yanqu123");
                        JSONObject result = JSONObject.parseObject(resp);
                        int status = result.getInteger("status");
                        if (status != 1) {
                            errorCrossServerIdList.add((long) processInfo.getServerId());
                        }
                    } catch (Exception e) {
                        errorCrossServerIdList.add((long) processInfo.getServerId());
                    } finally {
                        countDownLatch.countDown();
                    }
                });
            }
            //等待
            if (!countDownLatch.await(30, TimeUnit.SECONDS)) {
                ServerListMgr.getLogger().error("刷新超时");
            }
        } catch (Exception e) {
            ServerListMgr.getLogger().error("", e);
        }

        AdminResult result = AdminResult.defaultInstance();
        result.getData().put("serverIds", StringUtils.listToString(errorCrossServerIdList, ","));
        return result.toJsonString();
    }

    /**
     *  27.5 批量导入
     */
    @ResponseBody
    @RequestMapping(value = "batchCrossServerGroup", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String batchCrossServerGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        //收集channelId
        JSONArray list = jsonObject.getJSONArray("list");
        if(list.size() == 0){
            return AdminResult.failMsg("参数有误").toJsonString();
        }

        List<Integer> channelIdList = new ArrayList<>();

//        List<Map<String, Object>> addList = new ArrayList<>();
        List<ServerGroup> addList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject object = list.getJSONObject(i);
            int channelId = object.getIntValue("channelId");
            int rankFlag = object.getIntValue("rankFlag");
            String serverIds = object.getString("serverIds");
            int chatFlag = object.getIntValue("chatFlag");
            int wealthFlag = object.getIntValue("wealthFlag");
//            Map<String, Object> dataMap = new HashMap<>();
//            dataMap.put("crossRank", rankFlag);
//            dataMap.put("changTime", DateHelper.getCurrentSecond());
//            dataMap.put("serverList", StringUtils.stringToLongList(serverIds, ","));
//            dataMap.put("channelId", channelId);
//            dataMap.put("crossChat", chatFlag);
//            dataMap.put("crossMammon", wealthFlag);
//            addList.add(dataMap);
            ServerGroup data = new ServerGroup();
//            data.setGroupId(++maxGroupId);
            data.setCrossRank(rankFlag == 1);
            data.setCrossMammonState(wealthFlag);
            data.setCrossChat(chatFlag == 1);
//            data.setServerList(StringUtils.stringToLongList(serverIds, ","));
            data.setServerListStr(serverIds);
            data.setChannelId(channelId);
            if(!channelIdList.contains(channelId)){
                channelIdList.add(channelId);
            }
            addList.add(data);
        }

        if(channelIdList.size() == 0){
            return AdminResult.failMsg("渠道id缺失").toJsonString();
        }

        boolean del = new AdminCommonDaoImpl().deleteServerGroup(channelIdList);
        if(!del){
            return AdminResult.failMsg("删除渠道下的分组失败").toJsonString();
        }

        int maxGroupId = new AdminCommonDaoImpl().getCrossServerGroupMaxId();

//        for (Map<String, Object> dataMap : addList) {
//            dataMap.put("groupId", ++maxGroupId);
//        }
        for (ServerGroup group : addList) {
            group.setGroupId(++maxGroupId);
        }


        boolean result = new AdminCommonDaoImpl().batchInsertServerGroup(addList, DateHelper.getCurrentSecond());

        if(!result){
            return AdminResult.failMsg("批量插入失败").toJsonString();
        }

        return AdminResult.defaultInstance().toJsonString();
    }

}
